import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/network_utils.dart';
import '../../services/logger_service.dart';
import '../../models/account_ye_model.dart';
import 'package:gif/gif.dart';
import '../../manger/qysdk_manger.dart';
class AccountYePage extends StatefulWidget {
  const AccountYePage({super.key});

  @override
  State<AccountYePage> createState() => _AccountYePageState();
}

class _AccountYePageState extends State<AccountYePage> {
  final GlobalKey _questionMarkKey = GlobalKey();
  OverlayEntry? _overlayEntry;

  void _showExplanationPopup() {
    final renderBox = _questionMarkKey.currentContext?.findRenderObject() as RenderBox;
    final position = renderBox.localToGlobal(Offset.zero);
    final screenWidth = MediaQuery.of(context).size.width;

    _overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
        left: position.dx + 23, // 图标宽度18 + 右边距5
        top: position.dy - 10,
        child: Material(
          color: Colors.transparent,
          child: Container(
            width: screenWidth - position.dx - 38, // 总右边距15 + 23
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black12,
                  blurRadius: 10,
                  spreadRadius: 2
                )
              ]
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
            
                Padding(
                  padding: EdgeInsets.all(15),
                  child: RichText(
                    text: TextSpan(
                      text: AppLocalizations.of(context)!.theAccountBalanceIsStoredAndDisplayedInUSD,
                      style: TextStyle(
                        color: Color(0xFF666666),
                        fontSize: 12,
                        height: 1.5
                      )
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );

    Overlay.of(context).insert(_overlayEntry!);
  }

  void _removePopup() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }
  List<YueListModel>? _yeList;
  String balance = '0.00';

  Future<void> _fetchBalanceData() async {

    final response = await NetworkUtils.get(
      RequestCmd.memberBalanceLog,
      params: {'pageNum': 1, 'pageSize': 99999},
    );
    
    final model = YueModel.fromJson(response);
    if (model.code == 200) {
       setState(() {
          _yeList = model.data?.page!.records;
          balance = model.data?.balance.toString() ?? '0.00'; // 假设 balance 是一个字符串，你可能需要根据实际情况进行转换
        });
    } else {
    } 
  }

  @override
  void dispose() {
    _removePopup();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _fetchBalanceData();
  }

  Widget _buildBalanceCard() {
    return Padding(
      padding: const EdgeInsets.all(15),
      child: Container(
        height: 125,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          image: DecorationImage(
            image: AssetImage('assets/images/yuebg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 15),
              Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      if (_overlayEntry == null) {
                        _showExplanationPopup();
                      } else {
                        _removePopup();
                      }
                    },
                    child: Row(
                      children: [
                        Text(
                          '${AppLocalizations.of(context)!.accountBalance}（USD）',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 13,
                          ),
                        ),
                        SizedBox(width: 2),
                        Image.asset(
                          'assets/images/问号.png',
                          width: 18,
                          height: 18,
                          key: _questionMarkKey,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 15),
              RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      text: '\$',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 17,
                        fontWeight: FontWeight.bold
                      ),
                    ),
                    TextSpan(
                      text: balance,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 25,
                        fontWeight: FontWeight.bold
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _listItemView() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, right: 15, bottom: 80),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 15, right: 15, top: 20, bottom: 1),
              child: Align(
                alignment: Alignment.centerLeft,
                child: Stack(
                  children: [
                    Container(
                      width: isChineseLocale() ? 70 : 146,
                      height: 30,
                      alignment: Alignment.centerLeft,
                      child: Container(
                        height: 6,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(3),
                          gradient: LinearGradient(
                            colors: [
                              Color(0xFFFFEFAC),
                              Color(0xFFC8873E),                          
                            ],
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                          ),
                        ),
                      ),
                    ),
                    Positioned(
                      left: 0,
                      top: -5,
                      child: Text(
                        AppLocalizations.of(context)!.balanceDetails,
                        style: TextStyle(
                          color: Color(0xFF000000),
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: _yeList == null || _yeList!.isEmpty
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                            'assets/images/none.png',
                            width: 180,
                            height: 110,
                          ),
                          SizedBox(height: 3),
                          Text(
                            '${AppLocalizations.of(context)!.none}${AppLocalizations.of(context)!.balanceDetails}～',
                            style: TextStyle(
                              color: Color(0xFF000000),
                              fontSize: 15,
                            ),
                          ),
                        ],
                      ),
                    )
                  : ListView.builder(
                      itemCount: _yeList!.length,
                      itemBuilder: (context, index) {
                        final model = _yeList![index];
                        return Column(
                          children: [
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 5),
                              child: Column(
                                children: [
                                  const SizedBox(height: 5),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      SizedBox(
                                        width: MediaQuery.of(context).size.width - 140,
                                        child: Text(
                                          model.reason,
                                          style: const TextStyle(
                                            color: Color(0xFF000000),
                                            fontSize: 15,
                                          ),
                                          maxLines: 3,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                      Text(
                                        model.type == 0 
                                          ? '-\$${model.currentAmount}' 
                                          : '+\$${model.currentAmount}',
                                        style: TextStyle(
                                          color: model.type == 0 
                                            ? const Color(0xFFF61F03) 
                                            : const Color(0xFF000000),
                                          fontSize: 15,
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 8),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        model.createTime,
                                        style: const TextStyle(
                                          color: Color(0xFF999999),
                                          fontSize: 12,
                                        ),
                                      ),
                                      Text(
                                        '${AppLocalizations.of(context)!.accountBalance}:${model.currentBalance.toString()}' ,
                                        style: const TextStyle(
                                          color: Color(0xFF999999),
                                          fontSize: 12,
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 5),
                                ],
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 15),
                              child: const Divider(height: 1, color: Color(0xFFF5F5F5)),
                            ),
                          ],
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 48,
        title: Text(
          AppLocalizations.of(context)!.accountBalance,
          style: const TextStyle(fontSize: 17),
        ),
        actions: [
          IconButton(           
            icon: Gif(
                // Use the gifController instance
                fps: 10,
                autostart: Autostart.loop,
                image: AssetImage('assets/images/kefu_logo2.gif'),
                width: 42,
                height: 42,
                fit: BoxFit.cover,
              ),
            onPressed: () {
              QYSDK.showQYSession();
            },
          ),
        ],
      ),
      body: Column(
        children: [
          _buildBalanceCard(),
          Expanded(
            child: _listItemView(),
          ),
        ],
      ),
    );
  }
}